<template>
  <div class="chat-interface">
    <!-- 消息列表 - 固定高度，可滚动 -->
    <div class="messages-container" ref="messagesContainer">
      <div class="messages-wrapper">
        <div v-if="chatList.length === 0" class="empty-state">
          <!-- 主标题 -->
          <div class="welcome-section">
            <h1 class="text-2xl font-bold text-gray-800 mb-3"
              >我是电价政策智能助手，很高兴见到你</h1
            >
            <p class="text-gray-600 mb-8 text-lg">我可以帮助你查询电价政策，解答你的疑问。</p>
          </div>

          <!-- 猜你想问 -->
          <div class="suggested-questions-section">
            <h3 class="text-lg font-semibold text-gray-700 mb-4">猜你想问</h3>
            <div class="questions-grid">
              <button
                v-for="question in displayedQuestions"
                :key="question"
                @click="handleQuestionClick(question)"
                class="question-card"
              >
                {{ question }}
              </button>
            </div>
          </div>
        </div>

        <div v-else class="chat-messages">
          <ChatMessage
            v-for="message in chatList"
            :key="message.id"
            :message="message"
            :feedback-disabled="feedbackDisabled"
            @copy="handleCopy"
            @regenerate="handleRegenerate"
            @feedback="handleFeedback"
            @suggest-question="handleSuggestQuestion"
          />
        </div>
      </div>
    </div>

    <!-- 输入区域 - 固定在底部 -->
    <div class="input-container">
      <ChatInput
        :loading="isResponding"
        :disabled="feedbackDisabled"
        :control-clear="controlClearQuery"
        @send="handleSend"
        @stop="handleStop"
      />
    </div>

    <!-- 悬浮建议问题 -->
    <SuggestedQuestions
      :questions="suggestedQuestions"
      :visible="showSuggestedQuestions"
      :loading="loadingSuggestions"
      @question-click="handleSuggestedQuestionClick"
      @close="handleCloseSuggestions"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, watch, computed } from 'vue'
import { useToast } from 'vue-toast-notification'
import ChatMessage from './ChatMessage.vue'
import ChatInput from './ChatInput.vue'
import SuggestedQuestions from './SuggestedQuestions.vue'
import { getSuggestedQuestions } from '@/service'
import type { ChatItem, Feedbacktype, VisionFile, VisionSettings } from '@/types/app'

interface Props {
  chatList: ChatItem[]
  isResponding: boolean
  feedbackDisabled: boolean
  visionConfig?: VisionSettings
  controlClearQuery?: number
}

const props = defineProps<Props>()

const emit = defineEmits<{
  send: [message: string, files: VisionFile[]]
  feedback: [messageId: string, feedback: Feedbacktype]
  stop: []
  regenerate: [messageId: string]
}>()

const messagesContainer = ref<HTMLElement>()
const toast = useToast()

// 默认问题列表
const defaultQuestions = [
  '功率因数的标准值及其适用范围是多少',
  '某用户四月份用电1000度，执行0.90为标准值的功率因数调整电费，四月份实际功率因数为0.85，请计算该用户功率因数调整电费为多少?',
  '国家发展改革委关于完善风力发电上网电价政策的通知是什么',
  '农村"煤改电"区域集中供暖项目的电价政策是什么',
  '地方电网与山西电网间工商业用户结算电价调整后的标准是多少？',
  '地方电网配电价格的制定方法有哪些？',
  '电动自行车充电设施电费与服务费如何标示？',
  '执行居民合表电价的电动自行车充电设施电价标准是什么？',
  '风电项目何时全面实现平价上网？',
  '风电项目调试期上网电价如何确定？',
  '抽水蓄能电站容量电价标准是多少？',
  '功率因数0.85的用户执行0.90标准时如何计算电费增减？',
  '自备电厂系统备用费收取标准是什么？',
  '分布式光伏发电的电价补贴标准是多少？如何执行？',
  '煤电容量电价机制的执行范围和标准是什么？',
  '山西省对余热余压余气自备电厂的系统备用费政策有何调整？',
  '农林生物质发电项目小时均值超标如何核减补贴？',
  '发电企业与电网企业电费结算争议如何解决？',
  '跨省电能临时交易中紧急事故支援的电价如何确定？',
  '如何加强对建筑屋顶资源使用的统筹协调？',
  '深化燃煤发电市场化改革的总体思路是什么？',
  '分布式光伏项目2018年补贴标准如何规定？',
  '光伏扶贫项目电价政策有何特殊规定？',
  '功率因数标准值0.80适用于哪些用户？',
  '地方电网配电价格制定方法中的准许收入法如何计算？',
  '农村区域集中供暖项目按"峰谷时段计价方式"执行需满足什么条件？',
  '地方电网居民农业趸售电量调整后的结算电价是多少？'
]

// 随机选择5个问题用于显示
const displayedQuestions = computed(() => {
  const shuffled = [...defaultQuestions].sort(() => 0.5 - Math.random())
  return shuffled.slice(0, 5)
})

// 建议问题相关状态
const suggestedQuestions = ref<string[]>([])
const showSuggestedQuestions = ref(false)
const loadingSuggestions = ref(false)
const lastProcessedMessageId = ref<string>('')

// 计算最后一条AI消息
const lastAiMessage = computed(() => {
  const aiMessages = props.chatList.filter((msg) => msg.isAnswer && !msg.streaming)
  return aiMessages.length > 0 ? aiMessages[aiMessages.length - 1] : null
})

const handleSend = (message: string, files: File[]) => {
  const visionFiles: VisionFile[] = files.map((file) => ({
    type: file.type,
    url: URL.createObjectURL(file),
    upload_file_id: `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }))

  // 发送消息时隐藏建议问题
  hideSuggestedQuestions()

  emit('send', message, visionFiles)
}

const handleCopy = (content: string) => {
  navigator.clipboard
    .writeText(content)
    .then(() => {
      toast.success('消息已复制到剪贴板')
    })
    .catch((error) => {
      console.error('复制失败:', error)
      toast.error('复制失败')
    })
}

const handleRegenerate = (messageId: string) => {
  // 重新生成时隐藏建议问题
  hideSuggestedQuestions()

  console.log('重新生成消息:', messageId)
  toast.info('正在重新生成回答...')

  // 发出重新生成事件给父组件
  emit('regenerate', messageId)
}

const handleFeedback = (messageId: string, feedback: Feedbacktype) => {
  emit('feedback', messageId, feedback)
  toast.success(
    feedback.rating === 'like' ? '感谢您的正面反馈！' : '感谢您的反馈，我们会努力改进！'
  )
}

const handleSuggestQuestion = (question: string) => {
  // 处理消息内的建议问题点击
  console.log('消息内建议问题:', question)

  // 隐藏悬浮建议问题
  hideSuggestedQuestions()

  // 发送问题
  emit('send', question, [])
}

const handleSuggestedQuestionClick = (question: string) => {
  // 处理悬浮建议问题点击
  console.log('悬浮建议问题点击:', question)

  // 隐藏建议问题
  hideSuggestedQuestions()

  // 发送问题
  emit('send', question, [])
}

const handleCloseSuggestions = () => {
  hideSuggestedQuestions()
}

const handleStop = () => {
  emit('stop')
}

// 处理默认问题点击
const handleQuestionClick = (question: string) => {
  console.log('默认问题点击:', question)
  emit('send', question, [])
}

// 获取建议问题
const fetchSuggestedQuestions = async (messageId: string) => {
  if (!messageId || messageId === lastProcessedMessageId.value) {
    return
  }

  try {
    console.log('🔍 获取建议问题，消息ID:', messageId)
    loadingSuggestions.value = true

    const response = await getSuggestedQuestions(messageId)
    console.log('📝 建议问题API响应:', response)

    // 处理API响应
    let questions: string[] = []
    if (Array.isArray(response)) {
      questions = response
    } else if (response && typeof response === 'object') {
      if ('data' in response && Array.isArray(response.data)) {
        questions = response.data
      } else if ('questions' in response && Array.isArray(response.questions)) {
        questions = response.questions
      } else if ('suggested_questions' in response && Array.isArray(response.suggested_questions)) {
        questions = response.suggested_questions
      }
    }

    console.log('✅ 处理后的建议问题:', questions)

    if (questions.length > 0) {
      suggestedQuestions.value = questions
      showSuggestedQuestions.value = true
      lastProcessedMessageId.value = messageId

      toast.success(`获取到 ${questions.length} 个建议问题`)
    } else {
      console.log('⚠️ 没有获取到建议问题')
    }
  } catch (error) {
    console.error('❌ 获取建议问题失败:', error)
    toast.error('获取建议问题失败')
  } finally {
    loadingSuggestions.value = false
  }
}

// 隐藏建议问题
const hideSuggestedQuestions = () => {
  showSuggestedQuestions.value = false
  suggestedQuestions.value = []
}

// 自动滚动到底部
const scrollToBottom = (smooth = true) => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: smooth ? 'smooth' : 'auto'
      })
    }
  })
}

// 监听消息变化，自动滚动到底部
watch(
  () => props.chatList,
  (newList, oldList) => {
    console.log(`ChatInterface - 消息列表更新: ${oldList?.length || 0} -> ${newList.length}`)

    // 检查是否为流式更新（内容变化但消息数量不变）
    const isStreamingUpdate =
      oldList &&
      newList.length === oldList.length &&
      newList.some((msg, index) => {
        const oldMsg = oldList[index]
        return (
          oldMsg &&
          (msg.content !== oldMsg.content ||
            msg.streaming !== oldMsg.streaming ||
            msg.lastUpdated !== oldMsg.lastUpdated)
        )
      })

    // 如果是流式更新，记录详细信息
    if (isStreamingUpdate) {
      const streamingMessages = newList.filter((msg) => msg.streaming)
      console.log('检测到流式更新:', {
        streamingCount: streamingMessages.length,
        messages: streamingMessages.map((msg) => ({
          id: msg.id,
          contentLength: msg.content?.length || 0,
          streaming: msg.streaming,
          lastUpdated: msg.lastUpdated
        }))
      })
    }

    // 流式更新时使用平滑滚动，新消息时立即滚动
    scrollToBottom(!isStreamingUpdate)
  },
  { deep: true, immediate: false }
)

// 监听响应状态变化
watch(
  () => props.isResponding,
  (isResponding, wasResponding) => {
    if (isResponding) {
      // 开始响应时隐藏建议问题
      hideSuggestedQuestions()
      scrollToBottom()
    } else if (wasResponding && !isResponding) {
      // 响应结束时，获取建议问题
      console.log('🎯 AI响应结束，准备获取建议问题')

      // 延迟一下确保消息已经完全更新
      setTimeout(() => {
        const lastMessage = lastAiMessage.value
        if (lastMessage && lastMessage.id) {
          console.log('📋 最后一条AI消息:', lastMessage.id)
          fetchSuggestedQuestions(lastMessage.id)
        } else {
          console.log('⚠️ 没有找到最后一条AI消息')
        }
      }, 1000)
    }
  }
)

// // 监听最后一条AI消息的变化
// watch(lastAiMessage, (newMessage, oldMessage) => {
//   // 如果有新的AI消息且不在响应中，获取建议问题
//   if (newMessage &&
//       newMessage.id !== oldMessage?.id &&
//       !props.isResponding &&
//       !newMessage.streaming) {
//     console.log('🆕 检测到新的AI消息完成:', newMessage.id)
//     fetchSuggestedQuestions(newMessage.id)
//   }
// })
</script>

<style scoped>
.chat-interface {
  height: 89vh;
  display: flex;
  flex-direction: column;
  position: relative;
  background: inherit;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;
  background: linear-gradient(to bottom, #f8fafc 0%, #f1f5f9 100%);
  /* iOS Safari优化 */
  -webkit-overflow-scrolling: touch;
  /* 防止橡皮筋效果 */
  overscroll-behavior: contain;
  /* 确保消息容器可以正确滚动 */
  min-height: 0;
}

.messages-wrapper {
  max-width: 950px;
  margin: 0 auto;
  padding: 20px 20px 80px 20px;
  /* 底部留出输入框的空间 */
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  text-align: center;
  padding: 48px 20px;
}

.welcome-section {
  margin-bottom: 40px;
}

.suggested-questions-section {
  width: 100%;
  max-width: 600px;
}

.questions-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin-top: 16px;
}

.question-card {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px 20px;
  text-align: left;
  color: #374151;
  font-size: 14px;
  line-height: 1.5;
  transition: all 0.2s ease;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.question-card:hover {
  background: #f8fafc;
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
}

.question-card:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.chat-messages {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.input-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(
    to bottom,
    rgba(248, 250, 252, 0) 0%,
    rgba(248, 250, 252, 0.8) 20%,
    rgba(248, 250, 252, 1) 100%
  );
  padding: 16px 20px 20px 20px;
  border: none;
  z-index: 10;
  /* 确保输入框固定在底部 */
  flex-shrink: 0;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes bounce {
  0%,
  80%,
  100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .messages-wrapper {
    max-width: none;
    padding: 16px 16px 100px 16px;
    /* 移动端增加底部间距 */
  }

  .empty-state {
    min-height: 50vh;
    padding: 32px 16px;
  }

  .welcome-section h1 {
    font-size: 1.5rem;
  }

  .welcome-section p {
    font-size: 1rem;
  }

  .suggested-questions-section {
    max-width: none;
  }

  .question-card {
    padding: 14px 16px;
    font-size: 13px;
  }

  .input-container {
    /* 移动端调整输入框样式 */
    padding: 12px 16px 16px 16px;
  }
}
</style>
